<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\lib\util;

use lflow\exceptions\WorkFlowException;
use lflow\lib\util\Logger;
use ReflectionClass;

/**
 * 动态代理
 *
 * @author Mr.April
 * @since  1.0
 * @method intercept(\lflow\lib\util\workflow\Execution $execution)
 */
class ProxyHelper
{
    private mixed $obj;

    /**
     * @throws \lflow\lib\util\WorkFlowException
     */
    public function __construct(string $class)
    {
        if (interface_exists($class)) {
            throw new WorkFlowException("{$class} 接口不允许new");
        }
        if (!class_exists($class)) {
            throw new WorkFlowException("{$class} 类不存在啦");
        }
        $this->obj = new $class();
    }

    /**
     * @throws \lflow\lib\util\WorkFlowException
     */
    public function __call($name, $arguments)
    {
        try {
            $reflect = new ReflectionClass($this->obj);
            $method  = $reflect->getMethod($name);
            if (!$method) {
                throw new WorkFlowException("{$name} 方法名不存在");
            }
            if (!$method->isPublic() || $method->isAbstract()) {
                throw new WorkFlowException("{$name} 方法不能执行");
            }
            Logger::info('ProxyHelper before name:【' . $name . '】');
            $result = $method->invoke($this->obj, ...$arguments);
            Logger::info('ProxyHelper after name:【' . $name . '】');
            return $result;
        } catch (\ReflectionException $e) {
            throw new WorkFlowException($e->getMessage());
        }
    }
}

